import { defineStore } from 'pinia'
import { getUserInfo , updateUserInfo } from '@/api/user'
import { getAllPost } from '@/api/posts'
export const useStore = defineStore('userInfo', {
  state: () => {
    return {
      userData: {},
      commentData:{},
      current_post_id:{},
      searchData: ''
    }
  },
  // 定义getters，类似于computed，具有缓存功能
  getters: {},
  // 定义actions，类似于methods，用来修改state，做一些业务逻辑
  actions: {
    searchPost(content){
      getAllPost(1,'','',content).then((res) => {
        console.log(res);
      })
    },
    getUserDataByPinia() {
      // 获取用户信息
      let userId = localStorage.getItem('user')
      getUserInfo(userId).then((res) => {
        this.userData = res.data
        console.log(this.userData);
      })
    },
    updateUserDataByPinia(avatarUrl) {
      let data = {
        id: this.userData.id,
        username: this.userData.username,
        sex: this.userData.sex,
        birthday: this.userData.birthday,
        avatar: this.userData.avatar,
        college: this.userData.college,
        qqId: this.userData.qqId,
        avatar: this.userData.avatar,
      }
      if(avatarUrl!==this.userData.avatar){
        console.log('旧头像：' + this.userData.avatar);
        console.log('新头像：' + avatarUrl);
        data.avatar = avatarUrl
      }
      console.log(data);
      updateUserInfo(data).then((res) => {
        if(res.code == 1){
          ElNotification({
            title: '保存成功',
            message: '用户信息保存成功',
            type: 'success',
          })
        }else{
          ElNotification({
            title: 'error',
            message: '用户信息保存失败',
            type: 'error',
          })
        }
      })
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'userInfo',
        storage: localStorage,
      },
    ]
  }
})